import config from '@/config';
import EmitTask from '@socket/utils/emitTask';
import { constants, promises } from 'fs';
import { join } from 'path';
import { Socket } from 'socket.io';

import runCommand from './utils/runCommand';

export default async function (socket: Socket, params: any): Promise<void> {
  // 创建 EmitTask 实例，用于发送任务状态
  const emit = new EmitTask(socket, 'install-node-modules');
  // 开始任务
  emit.start();

  const { appId, repoName } = params;
  // 应用目录
  const appDir = join(config.appPath, appId);
  emit.info(`应用存储路径: ${appDir}`);
  // 确保应用目录存在,如果不存在则创建
  try {
    await promises.access(config.appPath, constants.F_OK);
  } catch (err) {
    try {
      await promises.mkdir(config.appPath, { recursive: true });
    } catch (mkdirErr) {
      emit.error(`创建应用数据存储路径失败: ${String(mkdirErr)}`);
      emit.errorEnd();
      return;
    }
  }

  // 仓库目录
  const repoDir = join(appDir, repoName);
  try {
    await promises.access(repoDir, constants.F_OK);
  } catch (e) {
    emit.error(`仓库目录不存在: ${String(e)}`);
    emit.errorEnd();
    return;
  }
  try {
    await runCommand(emit, 'pnpm', ['install'], {
      cwd: repoDir,
      shell: true,
    });
    emit.successEnd();
    return;
  } catch (err) {
    emit.error(String(err));
    emit.errorEnd();
    return;
  }
}
